package vns.client.presenter;

import java.util.ArrayList;
import java.util.List;

import vns.client.helper.RPCCall;
import vns.client.service.RoleServiceAsync;
import vns.client.view.RoleUI;
import vns.shared.RoleDTO;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

public class RolePresenter implements Presenter{

	@Override
	public void go(HasWidgets container) {
		container.clear();
		container.add(display.asWidget());
		doInitTable();
	}

	public interface Display{
		Button getUpdateButton();
		public Button getEditButton();
		List<RoleDTO> getListRow();
		boolean setListRow(List<RoleDTO> listRow);

		Widget asWidget();
		void render();
	}

	private final Display display;
	private final SimpleEventBus eventBus;
	private final RoleServiceAsync rpcService;
	
	/*
	 * Public method
	 */
	
	public RolePresenter(RoleUI view, SimpleEventBus eventBus, RoleServiceAsync model){
		this.display = view;
		this.eventBus = eventBus;
		this.rpcService= model;
		bind();
	}
	
	/*
	 * Private method
	 */
	
	private boolean bind(){
		display.getUpdateButton().addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				doUpdate();
			}
		});
		return false;
	}

	private void doInitTable() {
		new RPCCall<ArrayList<RoleDTO>>() {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Không load được Danh sách Vai trò!");
			}

			@Override
			public void onSuccess(ArrayList<RoleDTO> result) {
				display.setListRow(result);
				display.render();
			}

			@Override
			protected void callService(
				AsyncCallback<ArrayList<RoleDTO>> cb) {
				rpcService.Loadall(cb);
			}
		}.retry(3);
	}

	private void doUpdate(){
		new RPCCall<Void>() {
			
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Có lỗi khi đang cập nhật! \n " + caught.toString());
			}
			
			@Override
			public void onSuccess(Void result) {
				Window.alert("Cập nhật thành công! \n ");
				doInitTable();
			}
			
			@Override
			protected void callService(AsyncCallback<Void> cb) {
				rpcService.Updateall(display.getListRow(), cb);
			}
		}.retry(3);
	}
}
